package com.w.concurrent.executor.selfdefined;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 单例模式
 * https://blog.csdn.net/qq_25806863/article/details/71126867
 *
 * @author wangyiwen
 * @date 2018-10-30 00:21
 */
public class ExecutorUtils {

    private static ReentrantLock lock = new ReentrantLock();

    private static volatile ExecutorService executorService;


    /**
     * 使用lock
     *
     * @return
     */
//    public static ExecutorService getThreadPool() {
//        try {
//            if (null == executorService) {
//                lock.lock();
//                if (null == executorService) {
//                    RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
//                    executorService = new ThreadPoolExecutor(100, 100, 10, TimeUnit.SECONDS,
//                            new LinkedBlockingQueue<Runnable>(1000), handler);
//                }
//            }
//        } finally {
//            lock.unlock();
//        }
//        return executorService;
//    }

    /**
     * double-checked locking get threadPool
     *
     * @return
     */
    public static ExecutorService getThreadPool() {
        if (null == executorService) {
            synchronized (ExecutorUtils.class) {
                if (null == executorService) {
                    RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
                    executorService = new ThreadPoolExecutor(100, 100, 10, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>(1000), handler);
                }
            }
        }
        return executorService;
    }
}
